#include "logindialog.h"
#include "ui_logindialog.h"
#include "mainwindow.h"
#include "httpmgr.h"
#include <QPainter>
#include <QDebug>
#include <tcpmgr.h>
LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    //登录按钮中有注册按钮，将注册按钮也注册信号与槽
    connect(ui->pushButton_register,
            &QPushButton::clicked,
            this,
            &LoginDialog::switchRegister);

    ui->lineEdit_password->setEchoMode(QLineEdit::Password);


        ui->label_forget_pass->SetState("normal","hover","","selected","selected_hover","");

        connect(ui->label_forget_pass, &ClickedLabel::clicked, this, &LoginDialog::slot_forget_pwd);

        initHeader();
        initHttpHandler();

        //连接登录回包信号
        connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_login_mod_finish, this,
                &LoginDialog::slot_login_mod_finish);

        //连接tcp连接请求的信号和槽函数
        connect(this, &LoginDialog::sig_connect_tcp, TcpMgr::GetInstance().get(), &TcpMgr::slot_tcp_connect);
        //连接tcp管理者发出的连接成功信号
        connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_con_success, this, &LoginDialog::slot_tcp_con_finish);
        //连接tcp管理者发出的登陆失败信号
        connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_login_failed, this, &LoginDialog::slot_login_failed);
}

LoginDialog::~LoginDialog()
{
    delete ui;
    qDebug()<<"LoginDialog已被析构";
}

void LoginDialog::slot_forget_pwd()
{
    qDebug()<<"slot forget pwd";
    emit switchReset();
}

void LoginDialog::slot_login_mod_finish(ReqId id,
                                        QString res,
                                        ErrorCodes err)
{
    if(err != ErrorCodes::SUCCESS){
            showTip(tr("网络请求错误"),false);
            return;
        }

        // 解析 JSON 字符串,res需转化为QByteArray
        QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
        //json解析错误
        if(jsonDoc.isNull()){
            showTip(tr("json解析错误"),false);
            return;
        }

        //json解析错误
        if(!jsonDoc.isObject()){
            showTip(tr("json解析错误"),false);
            return;
        }


        //调用对应的逻辑,根据id回调。
        _handlers[id](jsonDoc.object());

        return;
}

void LoginDialog::initHeader()
{
    // 加载图片
        QPixmap originalPixmap(":/res/head_1.jpg");
          // 设置图片自动缩放
        qDebug()<< originalPixmap.size() << ui->label_image->size();
        originalPixmap = originalPixmap.scaled(ui->label_image->size(),
                Qt::KeepAspectRatio, Qt::SmoothTransformation);

        // 创建一个和原始图片相同大小的QPixmap，用于绘制圆角图片
        QPixmap roundedPixmap(originalPixmap.size());
        roundedPixmap.fill(Qt::transparent); // 用透明色填充

        QPainter painter(&roundedPixmap);
        painter.setRenderHint(QPainter::Antialiasing); // 设置抗锯齿，使圆角更平滑
        painter.setRenderHint(QPainter::SmoothPixmapTransform);

        // 使用QPainterPath设置圆角
        QPainterPath path;
        path.addRoundedRect(0, 0, originalPixmap.width(), originalPixmap.height(), 10, 10); // 最后两个参数分别是x和y方向的圆角半径
        painter.setClipPath(path);

        // 将原始图片绘制到roundedPixmap上
        painter.drawPixmap(0, 0, originalPixmap);

        // 设置绘制好的圆角图片到QLabel上
        ui->label_image->setPixmap(roundedPixmap);
}

void LoginDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips,false);
}

void LoginDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->label_tip->clear();
        return;
    }
    showTip(_tip_errs.first(),false);
}

void LoginDialog::showTip(QString tip, bool flag)
{
    ui->label_tip->setText(tr(tip.toUtf8()));
    if(flag){
        ui->label_tip->setProperty("state","normal");
    }else{
        ui->label_tip->setProperty("state","error");
    }
    repolish(ui->label_tip);
}

bool LoginDialog::checkUserValid(){

    auto user = ui->lineEdit_username->text();
    if(user.isEmpty()){
        AddTipErr(TipErr::TIP_USER_ERR,"User empty ");
        qDebug() << "User empty " ;
        return false;
    }

    return true;
}

bool LoginDialog::checkPwdValid(){
    auto pwd = ui->lineEdit_password->text();
    if(pwd.length() < 6 || pwd.length() > 15){
        AddTipErr(TipErr::TIP_PWD_ERR,"Pass length invalid");
        qDebug() << "Pass length invalid";
        return false;
    }

    return true;
}

void LoginDialog::on_pushButton_login_clicked()
{
    qDebug()<<"login btn clicked";
        if(checkUserValid() == false){
            return;
        }

        if(checkPwdValid() == false){
            return ;
        }

        auto user = ui->lineEdit_username->text();
        auto pwd = ui->lineEdit_password->text();
        //发送http请求登录
        QJsonObject json_obj;
        json_obj["email"] = user;
        json_obj["passwd"] = xorString(pwd);
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_login"),
                                            json_obj, ReqId::ID_LOGIN_USER,Modules::LOGINMOD);



}

void LoginDialog::slot_tcp_con_finish(bool bsuccess)
{
    if(bsuccess){
          showTip(tr("聊天服务连接成功，正在登录..."),true);
          QJsonObject jsonObj;
          jsonObj["uid"] = _uid;
          jsonObj["token"] = _token;

          QJsonDocument doc(jsonObj);
          QString jsonString = doc.toJson(QJsonDocument::Indented);

          //发送tcp请求给chat server 开始正式连接
          emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_CHAT_LOGIN, jsonString);

       }else{
          showTip(tr("网络异常"),false);
          enableBtn(true);
       }
}

bool LoginDialog::enableBtn(bool enabled)
{
    ui->pushButton_login->setEnabled(enabled);
    ui->pushButton_register->setEnabled(enabled);
    return true;
}

void LoginDialog::slot_login_failed(int err)
{
    QString result = QString("登录失败, err is %1")
                                 .arg(err);
        showTip(result,false);
        enableBtn(true);
}

void LoginDialog::initHttpHandler()
{
    //注册获取登录回包逻辑
    _handlers.insert(ReqId::ID_LOGIN_USER, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(error != ErrorCodes::SUCCESS){
            showTip(tr("参数错误"),false);
            return;
        }
        auto user = jsonObj["email"].toString();
//        showTip(tr("登录成功"), true);
//        qDebug()<< "user is " << user ;
        //发送信号通知tcpMgr发送长链接
        ServerInfo si;
        si.Uid = jsonObj["uid"].toInt();
        si.Host = jsonObj["host"].toString();
        si.Port = jsonObj["port"].toString();
        si.Token = jsonObj["token"].toString();

        _uid = si.Uid;
        _token = si.Token;
        qDebug()<< "email is " << user << " uid is " << si.Uid <<" host is "
                << si.Host << " Port is " << si.Port << " Token is " << si.Token;
        emit sig_connect_tcp(si);
    });
}
